from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404

from app import models
from app.models import UserInfo
from app.forms import LoginForm, UserForm  # 新增UserForm导入
from CNAS1 import settings
import os


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    form = LoginForm(data=request.POST)
    # 校验是否为空
    if not form.is_valid():
        return render(request, 'login.html', {'form': form})

    user_object = models.UserInfo.objects.filter(**form.cleaned_data).first()
    if not user_object:
        return render(request, 'login.html', {'form': form, 'error': "用户名或密码错误"})
    request.session['user_info'] = {'user_id': user_object.pk, 'username': user_object.username,
                                    'password': user_object.password, 'role': user_object.role,
                                    'full_name': user_object.full_name, 'email': user_object.email}
    return redirect('/add/')


def register(request):
    # 修改注册视图以使用UserForm表单类
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            # 保存用户
            user = form.save()
            return redirect('login')  # 注册成功后跳转到登录页面
        else:
            # 表单验证失败，返回错误信息
            return render(request, 'register.html', {'form': form})
    else:
        form = UserForm()
    return render(request, 'register.html', {'form': form})


def logout(request):
    request.session.clear()
    return redirect('/login/')


def user_list(request):
    """用户列表展示"""
    users = UserInfo.objects.all()
    return render(request, 'account/user_list.html', {'users': users})


def user_add(request):
    """添加用户"""
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('user_list')
    else:
        form = UserForm()
    return render(request, 'account/user_add.html', {'form': form})


def user_edit(request, user_id):
    """编辑用户"""
    user = get_object_or_404(UserInfo, id=user_id)
    if request.method == 'POST':
        form = UserForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            return redirect('user_list')
    else:
        form = UserForm(instance=user)
    return render(request, 'account/user_edit.html', {'form': form, 'user': user})


def user_delete(request, user_id):
    """删除用户"""
    user = get_object_or_404(UserInfo, id=user_id)
    user.delete()
    return redirect('user_list')



def account_info(request):
    # 从session中获取用户信息
    user_info = request.session.get('user_info')
    if not user_info:
        return redirect('/login/')
    
    user = UserInfo.objects.filter(username=user_info['username']).first()
    if not user:
        return redirect('/login/')
        
    signature_image = None
    
    # 检查是否存在签名图片
    signature_path = os.path.join(settings.BASE_DIR, 'templates', 'sign', f'{user.username}.png')
    if os.path.exists(signature_path):
        signature_image = f'/static/sign/{user.username}.png'
    
    if request.method == 'POST':
        # 处理签名图片上传
        if 'signature' in request.FILES:
            signature_file = request.FILES['signature']
            
            # 验证文件类型
            if signature_file.content_type.startswith('image/'):
                # 创建签名图片保存目录
                sign_dir = os.path.join(settings.BASE_DIR, 'templates', 'sign')
                if not os.path.exists(sign_dir):
                    os.makedirs(sign_dir)
                
                # 保存签名图片，以工程师ID命名
                file_path = os.path.join(sign_dir, f'{user.username}.png')
                with open(file_path, 'wb+') as destination:
                    for chunk in signature_file.chunks():
                        destination.write(chunk)
                
                # 更新签名图片路径
                signature_image = f'/static/sign/{user.username}.png'

    permissions = []
    if user.kfv_cert_permission:
        permissions.append('KFV权限')
    if user.kfc_cert_permission:
        permissions.append('KFC权限')
    if user.dwy_cert_permission:
        permissions.append('DWY权限')
    if user.ph_cert_permission:
        permissions.append('PH权限')
    if user.hma_cert_permission:
        permissions.append('HMA权限')
    if user.lz_cert_permission:
        permissions.append('LZ权限')
    if user.ddl_cert_permission:
        permissions.append('DDL权限')
    
    context = {
        'user': user,
        'signature_image': signature_image,
        'permissions': permissions
    }
    
    return render(request, 'account_info.html', context)